// 提交链接 https://leetcode.cn/problems/max-consecutive-ones-iii/submissions/550223559/
// 1004. 最大连续1的个数 III
// 完成日期： 2024.8.30
// c++ 使用二分枚举长度，双指针验证


class Solution {
public:
    int longestOnes(vector<int>& nums, int k) {
        nums.insert(nums.begin(), 0);
        for (int i = 1; i < nums.size(); i++) nums[i] += nums[i - 1];
        int l = 0, r = nums.size() - 1;
        while (l < r)
        {
            int mid = (l + r) / 2 + 1;
            if (solve(mid, k, nums)) l = mid;
            else r = mid - 1;
        }
        return l;
    }
    int solve(int n, int k, vector<int>& nums)
    {
        int l = 1, r = n;
        while (r < nums.size())
        {
            if (n - nums[r] + nums[l - 1] <= k)
            {
                return 1;
            }
            l += 1; r += 1;
        }
        return 0;
    }
};